//
//  GCMenuSlefMessageViewController.m
//  GoldChampion
//
//  Created by coder on 2018/4/12.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//


#import "STTools_CoversationListViewController.h"
#import "STTools_CoversationDetailViewController.h"
#import "STTools_MessageListener.h"


@interface STTools_CoversationListViewController ()<STTools_CountDownMangerDelegate>
@property(nonatomic, assign) BOOL                     canAutoRefresh;/**< canAutoRefresh = yes 时，viewWillAppear 将会刷新 */
@property(nonatomic, strong) NSArray                     *roomArray;/**<  */
@end

@implementation STTools_CoversationListViewController

- (instancetype)initWithDisplayConversationTypes:(NSArray *)displayConversationTypeArray collectionConversationType:(NSArray *)collectionConversationTypeArray{
    if (self == [super initWithDisplayConversationTypes:displayConversationTypeArray collectionConversationType:collectionConversationTypeArray]) {
        
        [self refreshAllUnredCount];
    }
    return self;
}
- (void)dealloc{
    DDLogInfo(@"STTools_CoversationListViewController dealloc");
}
#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColor.blackColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:17]}];
    self.navigationController.navigationBar.barTintColor =  [UIColor whiteColor];
    
//    self.conversationListDataSource = [[RCIMClient sharedRCIMClient] getTopConversationList:self.collectionConversationTypeArray].mutableCopy;
    self.view.backgroundColor = UIColor.whiteColor;
    self.title = @"消息";
    [self stoneobs_ui_configSubView];
//    [self.conversationListTableView registerClass:TreeHoleCoversationTableViewCell.class forCellReuseIdentifier:@"TreeHoleCoversationTableViewCell"];
    [self refreshAllUnredCount];

    
    [STTools_CountDownManger.manger stoneobs_fun_addDelegate:self];
    [self countDownManger:STTools_CountDownManger.manger everySecendRun:4];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.canAutoRefresh) {
        [self refreshAllUnredCount];
        [self.conversationListTableView reloadData];
    }
    [self countDownManger:STTools_CountDownManger.manger everySecendRun:4];

}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.canAutoRefresh = YES;
//    [TreeHoleMessageAlertView stoneobs_fun_showMessageAlertViewWithMessageModel:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource{
    NSMutableArray * dealArray = dataSource.mutableCopy;
    
    RCConversationModel * fmodel = dataSource.firstObject;
    RCConversationModel * smodel;
    if (dataSource.count > 1) {
        smodel =  dataSource[1];
    }
//    if ([fmodel.senderUserId isEqualToString:@"system"] && [smodel.senderUserId isEqualToString:@"sysOrder"]) {
//        return dealArray;
//    }
    for (RCConversationModel * model in dataSource) {
        model.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        
        /*
         取消强制排序
        if ([model.senderUserId isEqualToString:@"system"]) {
            [dealArray removeObject:model];
            [dealArray insertObject:model atIndex:0];
//            [[RCIMClient sharedRCIMClient] setConversationToTop:1 targetId:@"system" isTop:YES];
        }
        if ([model.senderUserId isEqualToString:@"sysOrder"]) {
            [dealArray removeObject:model];
            [dealArray insertObject:model atIndex:0];
//            [[RCIMClient sharedRCIMClient] setConversationToTop:1 targetId:@"sysOrder" isTop:YES];
        }
*/
    }
    
    return dealArray;
}
#pragma mark --subView
- (void)stoneobs_ui_configSubView{
    __weak typeof(self) weakSelf =  self;

    //配置无数据图
    self.conversationListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.conversationListTableView.frame = CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, STONEOBS_UI_UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop - TMUtils.stoneobs_fun_get_navgationBarBootom);
    self.conversationListTableView.contentInset = UIEdgeInsetsZero;
    self.emptyConversationView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, 100, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"暂无消息" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    if (self == self.navigationController.childViewControllers.firstObject) {
    }else{
        self.conversationListTableView.frame = CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, STONEOBS_UI_UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop - TMUtils.stoneobs_fun_get_navgationBarBootom + 49);
    }
}
#pragma mark --接受到消息通知
- (void)didReceiveMessageNotification:(NSNotification *)notification{
//    [super didReceiveMessageNotification:notification];
    NSNumber *left = [notification.userInfo objectForKey:@"left"];
    RCMessage *message = notification.object;
    
    if ([message.content isKindOfClass:NSDictionary.class]) {
        //取消无法识别的自定义消息
        return;
    }

    
    if (message.objectName.length < 2) {
        //取消无法识别的自定义消息
        return;
    }
    
    
    RCConversationModel *customModel = [RCConversationModel new];
    customModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
    customModel.extend = @"";
    customModel.conversationType = message.conversationType;
    customModel.targetId = message.targetId;
    customModel.sentTime = message.sentTime;
    customModel.receivedTime = message.receivedTime;
    customModel.senderUserId = message.senderUserId;
    customModel.lastestMessage = message.content;
    NSInteger unred =  [[RCIMClient sharedRCIMClient] getUnreadCount:message.conversationType targetId:message.targetId];
    customModel.unreadMessageCount = unred;
    if (message.conversationType == ConversationType_PRIVATE || message.conversationType == ConversationType_GROUP) {
         [self asyncMainQueueDealModel:customModel left:left.integerValue];
    }
    //系统
    if ([customModel.senderUserId isEqualToString:@"system"] && [message.content isKindOfClass:RCTextMessage.class]) {

       
    }
    //订单邀约
    if ([customModel.senderUserId isEqualToString:@"sysOrder"] && [message.content isKindOfClass:RCTextMessage.class]) {

    }
}
- (void)asyncMainQueueDealModel:(RCConversationModel*)model left:(NSInteger)left{
    [self refreshConversationTableViewWithConversationModel:model];
    if (0 == left) {
        [super refreshConversationTableViewIfNeeded];
    }
    [self refreshAllUnredCount];
}
#pragma mark --重写cell
//-(CGFloat)rcConversationListTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return uitabe.TreeHole_cellHeight;
//}
//-(RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    TreeHoleCoversationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TreeHoleCoversationTableViewCell"];
//    RCConversationModel * model = self.conversationListDataSource[indexPath.row];
//    cell.model = model;
//    return cell;
//}
//- (void)rcConversationListTableView:(UITableView *)tableView
//                 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
//                  forRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    if(editingStyle == UITableViewCellEditingStyleDelete){
//        RCConversationModel *model = self.conversationListDataSource[indexPath.row];
//        [[RCIMClient sharedRCIMClient] removeConversation:model.conversationType targetId:model.targetId];
//        [[RCIMClient sharedRCIMClient] deleteMessages:model.conversationType targetId:model.targetId success:^{
//
//        } error:^(RCErrorCode status) {
//
//        }];
//        [self.conversationListDataSource removeObjectAtIndex:indexPath.row];
//        [self.conversationListTableView reloadData];
//        [self refreshAllUnredCount];
//    }
//}
//#pragma mark --Private Method
- (void)refreshAllUnredCount{
    //更新所有未读数量
    dispatch_async(dispatch_get_main_queue(), ^{
        NSInteger allunred = [[RCIMClient sharedRCIMClient] getUnreadCount:self.displayConversationTypeArray];
        if (allunred) {
             [self.rt_navigationController.tabBarItem setBadgeValue:@(allunred).description];
        }else{
             [self.rt_navigationController.tabBarItem setBadgeValue:nil];
        }
       
    });

}
- (void)countDownManger:(STTools_CountDownManger *)countDownManger everySecendRun:(NSInteger)runSectends{
    BOOL autoRefrsh = NO;
    if ((id)TMUtils.stoneobs_fun_get_currentTopController == self) {
         autoRefrsh = 1;
    }
    if (runSectends % 4 == 0 && autoRefrsh) {
        //刷新
        NSMutableArray * user_array = NSMutableArray.new;
        for (RCConversationModel * model in self.conversationListDataSource) {
            if (model.conversationType == ConversationType_PRIVATE) {
                if (![model.targetId isEqualToString:@"system"] && ![model.targetId containsString:@"admin"]) {
                     [user_array addObject:model.targetId];
                }else{
//                    [TreeHoleUserDataController stoneobs_fun_fetchRCUserInfoWithUser_id:model.targetId handle:^(RCUserInfo * info) {
//                        [RCIM.sharedRCIM refreshUserInfoCache:info withUserId:model.targetId];
//                        [self.conversationListTableView reloadData];
//                        [STTools_RcimUserCacheManger.manger saveUserInfoIfNeed:info];
//                    }];
                }
            }
            if (model.conversationType == ConversationType_GROUP) {
                if (![model.targetId isEqualToString:@"system"]) {

                }
            }


           
        }
        //批量获取
        NSString * user_ids = [user_array componentsJoinedByString:@","];
//        [TreeHoleUserDataController stoneobs_fun_fetchMoreRCUserInfosWithUser_id:user_ids handle:^(NSArray<THUserModel *> * _Nonnull array) {
//            for (THUserModel * user in array) {
//                [RCIM.sharedRCIM refreshUserInfoCache:user.userInfo withUserId:user.user_id];
//                [STTools_RcimUserCacheManger.manger saveUserInfoIfNeed:user.userInfo];
//            }
//            [self.conversationListTableView reloadData];
//        }];
    }
}
#pragma mark --Action Method

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath{
    NSString * userId = model.targetId;
    if ([userId containsString:@"system"]) {
        //系统消息
//        TreeHoleChatSysytemViewController * vc = TreeHoleChatSysytemViewController.new;
//        vc.systemUserID = userId;
//        [self pushViewController:vc animated:YES];
        
    }  else  if ([userId containsString:@"sysCustomer"]) {
//        TreeHoleHelpSystemViewController * vc = TreeHoleHelpSystemViewController.new;
//        vc.systemUserID = userId;
//        [self pushViewController:vc animated:YES];
        
    }else if ([userId containsString:@"sysOrder"]){
        //邀约信息
//        TreeHoleContactOrderViewController * vc = TreeHoleContactOrderViewController.new;
//        vc.orderUserID = userId;
//        [self pushViewController:vc animated:YES];
    }
    else{
//        TreeHoleChatDetailViewController * vc = [[TreeHoleChatDetailViewController alloc] initWithConversationType:model.conversationType targetId:model.targetId];
//        [self pushViewController:vc animated:YES];
    }

}
@end
